package com.pms.partitionPoints.web;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.partitionPoints.bean.OrgBean;
import com.pms.partitionPoints.entity.KyOrganizationEquipment;
import com.pms.partitionPoints.service.IKyGroupOrganizationService;
import com.pms.partitionPoints.service.IKyOrganizationEquipmentService;
import com.pms.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.web.bind.annotation.*;
import com.pms.controller.BaseController;
import com.pms.partitionPoints.service.IKyOrganizationService;
import com.pms.partitionPoints.entity.KyOrganization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("kyOrganization")
@Api(value="分区管理",description = "分区管理")
public class KyOrganizationController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    IKyOrganizationService kyOrganizationService;
    @Autowired
    IKyGroupOrganizationService kyGroupOrganizationService;
    @Autowired
    IKyOrganizationEquipmentService kyOrganizationEquipmentService;

    /**
         * 新增
         * @param entity
         * @return
         */
    @RequestMapping(value = "add",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分区新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name="parentId",value="上级分区id",required = true,dataType = "Integer",paramType="application/json"),
            @ApiImplicitParam(name="name",value="分区名称",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="code",value="分区编码",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="organizationgradeid",value="级别id--根据上级级别id加1",required = true,dataType = "Integer",paramType="application/json"),
            @ApiImplicitParam(name="linkman",value="联系人名称",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="linkphone",value="联系人电话",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="description",value="分区简介",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="monitoringsites",value="分区边界点",required = false,dataType = "String",paramType="application/json")
    })
    public R add(@RequestBody KyOrganization entity){
        if(entity.getParentid()==null){
            throw  new RRException("父级id不能为空");
        }
        Assert.isNull(entity.getOrganizationgradeid(),"级别id不能为空");
        Assert.isBlank(entity.getName(),"分区名称不能为空");
        Assert.isBlank(entity.getCode(),"分区编码不能为空");
        Assert.isBlank(entity.getLinkman(),"联系人不能为空");
        Assert.isBlank(entity.getLinkphone(),"联系电话不能为空");
        Assert.isBlank(entity.getMonitoringsites(),"分区边界点坐标不能为空");
        entity.setCreatetime(new Date());
        entity.setStatus(1);
        int count = kyOrganizationService.selectCount(new EntityWrapper<KyOrganization>().eq("name",entity.getName()).eq("code",entity.getCode()));
        if(count>0){
            return R.error("系统内已有此分区名称");
        }
        kyOrganizationService.insert(entity);
        return R.ok();
    }
    /**
     * 修改
     * @param entity
     * @return
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分区修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name="parentId",value="上级分区id",required = true,dataType = "Integer",paramType="application/json"),
            @ApiImplicitParam(name="name",value="分区名称",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="code",value="分区编码",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="linkman",value="联系人名称",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="linkphone",value="联系人电话",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="description",value="分区简介",required = true,dataType = "String",paramType="application/json"),
            @ApiImplicitParam(name="monitoringsites",value="分区边界点",required = false,dataType = "String",paramType="application/json")
    })
    public R update(@RequestBody KyOrganization entity){
        Assert.isNull(entity.getOrganizationgradeid(),"级别不能为空");
        Assert.isNull(entity.getParentid(),"父级id不能为空");
        Assert.isBlank(entity.getName(),"分区名称不能为空");
        Assert.isBlank(entity.getCode(),"分区编码不能为空");
        Assert.isBlank(entity.getLinkman(),"联系人不能为空");
        Assert.isBlank(entity.getLinkphone(),"联系电话不能为空");
        Assert.isBlank(entity.getMonitoringsites(),"分区边界点坐标不能为空");
        Assert.isNull(entity.getStatus(),"状态不能为空");
        entity.setUpdatetime(new Date());
        kyOrganizationService.updateById(entity);
        return R.ok();
    }

    /**
 * 删除
 * @param id
 * @return
 */
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    @ApiOperation(value = "分区删除")
    @ApiImplicitParam(name="id",value="分区id",required = true,dataType = "Integer",paramType="form")
    public R deleteById(@PathVariable Integer id){
        Assert.isNull(id,"分区id不能为空");
        //返回当前id和所有下级id集合
        List<String> idList = kyOrganizationService.getOrgIdsByCurrentId(id);
        try{
            kyOrganizationService.deleteOrgByIdList(idList);
        }catch (Exception e){
            return  R.error("分区删除异常");
        }
        return R.ok();
    }


    /**
     * findByID
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "分区详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="分区id",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="orgMaxId",value="顶级分区id",required = true,dataType = "int",paramType="form")
    })
    public R findById(@PathVariable int id){
        Assert.isNull(id,"分区id不能为空");
        KyOrganization ko = kyOrganizationService.selectById(id);
        Integer parentId = ko.getParentid();
        KyOrganization kyOrganization = kyOrganizationService.selectById(parentId);
        Map<String,Object> map = new HashMap<>();
        map.put("ko",ko);
        map.put("parentName",kyOrganization.getName());
        return R.ok().put("data",map);
    }


    @RequestMapping(value = "/page",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "分区分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="limit",value="分页条数",required = false,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="offset",value="分页条数",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="orgId",value="分区id",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="strName",value="搜索字段",required = false,dataType = "String",paramType="form")
    })
    public R page(@RequestParam(defaultValue = "10") int limit, @RequestParam(defaultValue = "1")int offset,Integer orgId,String strName){
        KyOrganization kyOrganization = kyOrganizationService.selectById(orgId);
        Assert.isNull(kyOrganization,"没有对应的分区");
        Page<KyOrganization> page = new Page<KyOrganization>(offset,limit);
        List<String> idList = new ArrayList<>();
        if(kyOrganization.getOrganizationgradeid()==1){//如果是顶级分区
            String type = request.getHeader("X-groupType");//type:1.系统默认 2.自定义
            Assert.isBlank(type,"用户类型不能为空");
            String companyCode = request.getHeader("X-Code");
            Assert.isBlank(companyCode,"系统编码不能为空");
            String roleId = request.getHeader("X-groupId");
            Assert.isBlank(roleId,"角色id不能为空");
            Assert.isNull(orgId,"机构id不能为空");
            if(type.equals("2")){
                String ids = kyGroupOrganizationService.getOrgIdsStrByGroupId(roleId);
                String [] arr = ids.split(",");
                if(arr.length>0){
                    for(int i=0;i<arr.length;i++){
                        if(!orgId.toString().equals(arr[i])){
                            idList.add(arr[i]);
                        }
                    }
                }
            }else{
                idList = kyOrganizationService.getOrgIdsByCurrentId(orgId);
            }
        }else{
            idList = kyOrganizationService.getOrgIdsByCurrentId(orgId);
        }
        Wrapper<KyOrganization> ew = new EntityWrapper<KyOrganization>().in("id",idList);
        ew.ne("organizationGradeId",1);
        if(!StringUtils.isBlank(strName)){
            ew.and("(name like ('%"+strName+"%') or code like ('%"+strName+"%') or linkMan like ('%"+strName+"%') or linkPhone like ('%"+strName+"%'))");
//            ew.and().like("name",strName).or().like("code",strName).or().like("linkMan",strName).or().like("linkPhone",strName);
        }
        page = kyOrganizationService.selectPage(page,ew);
        return R.ok().put("data",page);
    }

    @RequestMapping(value = "/all",method = RequestMethod.GET)
    @ResponseBody
    public List<KyOrganization> all(){
        return kyOrganizationService.selectList(null);
    }

    /**
     *根据角色查询对应的分区展示
     * @param
     * @return
     */
    @RequestMapping(value = "/findByGroupId",method = RequestMethod.GET)
    @ResponseBody
    public List<OrgBean> findByGroupId(HttpServletRequest request){
        String type = request.getHeader("X-groupType");//type:1.系统默认 2.自定义
        Assert.isBlank(type,"用户类型不能为空");
        String companyCode = request.getHeader("X-Code");
        Assert.isBlank(companyCode,"公司编码不能为空");
        String roleId = request.getHeader("X-groupId");
        Assert.isBlank(roleId,"角色id不能为空");
        Long groupId = Long.valueOf(roleId);
        if(type.equals("1")){
            groupId = null;
        }
        //角色所有的分区
        List<OrgBean> objList = kyOrganizationService.selectByGroupIdAndCode(groupId,companyCode);
        //分区对应的id集合
        List<Integer> idList = new ArrayList<>();
        //对应的parentId集合
//        List<Long> parentIdList = new LinkedList<>();
        Set<Integer> parentIdList = new HashSet<Integer>();
        //返回树结构
        List<OrgBean> newList = new ArrayList<OrgBean>();
        for(OrgBean bean:objList){
            idList.add(bean.getId());
            parentIdList.add(bean.getParentId());
        }
        if(objList.size()>0){
            for(OrgBean bean:objList){
                Integer id = bean.getId();
                Integer parentId = bean.getParentId();
                //父级id不在id集合内，则它是顶级
                if(!idList.contains(parentId)){
                    bean = kyOrganizationService.sortList(id,objList,bean,parentIdList);
                    if(type.equals("1")){
                        List<OrgBean> list= kyOrganizationService.getEquipmentsByOrgId(id);
                        bean.getChildren().addAll(list);
                    }
                    newList.add(bean);
                }
            }
        }
        return newList;
    }

    @RequestMapping(value = "/getMeasurePage",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "计量分区分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="limit",value="分页条数",required = false,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="offset",value="当前页码",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="orgId",value="分区id",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="strName",value="搜索字段",required = false,dataType = "String",paramType="form")
    })
    public R getMeasurePage(@RequestParam(defaultValue = "10") int limit, @RequestParam(defaultValue = "1")int offset,Integer orgId,String strName){
        KyOrganization kyOrganization = kyOrganizationService.selectById(orgId);
        Assert.isNull(kyOrganization,"没有对应的分区");
        List<String> idList = new ArrayList<>();
        if(kyOrganization.getOrganizationgradeid()==1){//如果是顶级分区
            String type = request.getHeader("X-groupType");//type:1.系统默认 2.自定义
            Assert.isBlank(type,"用户类型不能为空");
            String companyCode = request.getHeader("X-Code");
            Assert.isBlank(companyCode,"系统编码不能为空");
            String roleId = request.getHeader("X-groupId");
            Assert.isBlank(roleId,"角色id不能为空");
            Assert.isNull(orgId,"机构id不能为空");
            if(type.equals("2")){
                String ids = kyGroupOrganizationService.getOrgIdsStrByGroupId(roleId);
                String [] arr = ids.split(",");
                if(arr.length>0){
                    for(int i=0;i<arr.length;i++){
                        if(!orgId.toString().equals(arr[i])){
                            idList.add(arr[i]);
                        }
                    }
                }
            }else{
                idList = kyOrganizationService.getOrgIdsByCurrentId(orgId);
            }
        }else{
            idList = kyOrganizationService.getOrgIdsByCurrentId(orgId);
        }
//        String companyCode = request.getHeader("X-Code");
//        Assert.isBlank(companyCode,"系统编码不能为空");
//        if(orgId==null){
//            KyOrganization ko = kyOrganizationService.selectOne(new EntityWrapper<KyOrganization>().eq("code",companyCode).eq("organizationGradeId",1));
//            orgId = ko.getId();
//        }
        Page<Map<String,Object>> page = new Page<Map<String,Object>>(offset,limit);
        StringBuffer orgIds = new StringBuffer();
        if(idList.size()>0){
            for(String id:idList){
                if(orgIds.length()!=0){
                    orgIds.append(",");
                }
                orgIds.append(id);
            }
        }
        page = kyOrganizationService.queryOrgPage(page,new EntityWrapper<KyOrganization>(),orgIds.toString(),strName);
        return R.ok().put("data",page);
    }

    /**
     * 计量分区--根据分区id查询对应的测点
     *
     * @param orgId
     * @return
     */
    @RequestMapping(value = "/findEquipmentsByOrgId",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据分区id查询对应的计量测点(返回普通测点和计量测点)")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orgId",value="分区id",required = true,dataType = "Integer",paramType="form")
    })
    public R findEquipmentsByOrgId(Integer orgId){
        Assert.isNull(orgId,"分区id不能为空");
        Wrapper<KyOrganizationEquipment> wp = new EntityWrapper<KyOrganizationEquipment>();
        wp.eq("koe.organizationId",orgId);
        wp.eq("kei.status",1);
        wp.eq("koe.direction",5);
        List<Map<String,Object>> list = kyOrganizationService.getEquipmentsByOrgId(wp);
        Wrapper<KyOrganizationEquipment> wrapper = new EntityWrapper<KyOrganizationEquipment>();
        wrapper.eq("koe.organizationId",orgId);
        wrapper.eq("kei.status",1);
        wrapper.in("koe.direction","0,1");
        List<Map<String,Object>> measureList = kyOrganizationService.getEquipmentsByOrgId(wrapper);
        Map<String,Object> map = new HashMap<>();
        map.put("list",list);
        map.put("measureList",measureList);
        return R.ok().put("data",map);
    }

    /**
     * 计量分区--根据分区id查询对应的测点
     *
     * @param orgId
     * @return
     */
    @RequestMapping(value = "/findEquipmentListByOrgId",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据分区id查询对应的计量测点(只返回计量测点)")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orgId",value="分区id",required = true,dataType = "Integer",paramType="form")
    })
    public R findEquipmentListByOrgId(Integer orgId){
        Assert.isNull(orgId,"分区id不能为空");
        Wrapper<KyOrganizationEquipment> wrapper = new EntityWrapper<KyOrganizationEquipment>();
        wrapper.eq("koe.organizationId",orgId);
        wrapper.eq("kei.status",1);
        wrapper.in("koe.direction","0,1");
        List<Map<String,Object>> measureList = kyOrganizationService.getEquipmentsByOrgId(wrapper);
        int inCount = 0;
        int outCount = 0;
        Map<String,Object> map = new HashMap<>();
        for(Map<String,Object> m:measureList){
            Integer direction = (Integer)m.get("direction");
            if(direction==0){
                inCount += 1;
            }else{
                outCount += 1;
            }
        }
        map.put("measureList",measureList);
        map.put("inCount",inCount);
        map.put("outCount",outCount);
        return R.ok().put("data",map);
    }

    /**
     *
     * 根据分区ids 查询对应的测点
     * @param orgIds
     * @return
     */
    @RequestMapping(value = "/getEquipmentsByOrgIds",method = RequestMethod.GET)
    @ResponseBody
    @ApiImplicitParams({
                @ApiImplicitParam(name="orgIds",value="分区ids,字符串拼接",required = true,dataType = "String",paramType="json/app")
    })
    public R getEquipmentByOrgId(String orgIds){
        Assert.isBlank(orgIds,"分区ids 不能为空");
        List<Map<String,Object>> list = kyOrganizationService.getEquipmentsByOrgIds(orgIds);
        return R.ok().put("EquipmentList",list);
    }


    /**
     * 计量分区测点添加
     * @param list
     * @return
     */
    @RequestMapping(value = "/insertEquipmentsByOrgId",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "计量分区添加")
    @ApiImplicitParams({
            @ApiImplicitParam(name="organizationid",value="分区id(实体字段)",required = true,dataType = "Integer",paramType="application/json"),
            @ApiImplicitParam(name="equipmentid",value="测点id(实体字段)",required = true,dataType = "Integer",paramType="application/json"),
            @ApiImplicitParam(name="direction",value="测点相对于分区的流向:0.流出 1.流入 5.普通测点(没有流向)(实体字段)",required = true,dataType = "Integer",paramType="application/json")
    })
    public R insertEquipmentsByOrgId(@RequestBody List<KyOrganizationEquipment> list){
        if(list.size()==0){
            return R.error("集合不能为空");
        }
        Integer orgId = list.get(0).getOrganizationid();
        List<KyOrganizationEquipment> koList = kyOrganizationEquipmentService.selectList(new EntityWrapper<KyOrganizationEquipment>().eq("organizationId",orgId));
        if(koList.size()==0){
            return R.error("此分区没有关联的测点");
        }
        for(int i=0;i<koList.size();i++){
            KyOrganizationEquipment ko = koList.get(i);
            Integer equId = koList.get(i).getEquipmentid();
            for(int j=0;j<list.size();j++){
                Integer id = list.get(j).getEquipmentid();
                if(id.intValue()==equId.intValue()){
                    list.get(j).setId(ko.getId());
                }
            }
            ko.setDirection(5);
        }
        kyOrganizationEquipmentService.updateBatchById(koList);
        kyOrganizationEquipmentService.updateBatchById(list);
        return R.ok();
    }

    /**
     * 计量分区测点添加(当分区计量测点为空时)
     * @param orgId
     * @return
     */
    @RequestMapping(value = "/insertMeasureEquipmentsByOrgId",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "计量分区添加(当分区计量测点为空时)")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orgId",value="分区id",required = true,dataType = "Integer",paramType="form")
    })
    public R insertMeasureEquipmentsByOrgId(Integer orgId){
        Assert.isNull(orgId,"对应的分区id不能为空");
        List<KyOrganizationEquipment> koList = kyOrganizationEquipmentService.selectList(new EntityWrapper<KyOrganizationEquipment>().eq("organizationId",orgId));
        if(koList.size()==0){
            return R.error("此分区没有关联的测点");
        }
        for(KyOrganizationEquipment ko:koList){
            ko.setDirection(5);
        }
        kyOrganizationEquipmentService.updateBatchById(koList);
        return R.ok();
    }

    /**
     *根据角色查询对应的分区展示(不带测点)
     * @param
     * @return
     */
    @RequestMapping(value = "/findOrgByGroupIdAndRoleType",method = RequestMethod.GET)
    @ResponseBody
    public List<OrgBean> findOrgByGroupIdAndRoleType(HttpServletRequest request){
        String type = request.getHeader("X-groupType");//type:1.系统默认 2.自定义
        Assert.isBlank(type,"用户类型不能为空");
        String companyCode = request.getHeader("X-Code");
        Assert.isBlank(companyCode,"系统编码不能为空");
        String roleId = request.getHeader("X-groupId");
        Assert.isBlank(roleId,"角色id不能为空");
        Long groupId = Long.valueOf(roleId);
        if(type.equals("1")){
            groupId = null;
        }
        //角色所有的分区
        List<OrgBean> objList = kyOrganizationService.selectByGroupIdAndCode(groupId,companyCode);
        //分区对应的id集合
        List<Integer> idList = new ArrayList<>();
        Set<Integer> parentIdList = new HashSet<Integer>();
        //返回树结构
        List<OrgBean> newList = new ArrayList<OrgBean>();
        for(OrgBean bean:objList){
            idList.add(bean.getId());
            parentIdList.add(bean.getParentId());
        }
        if(objList.size()>0){
            for(OrgBean bean:objList){
                Integer id = bean.getId();
                Integer parentId = bean.getParentId();
                //父级id不在id集合内，则它是顶级
                if(!idList.contains(parentId)){
                    bean = kyOrganizationService.sortOrgList(id,objList,bean,parentIdList);
                    newList.add(bean);
                }
            }
        }
        return newList;
    }


    /**
     *根据角色查询对应的分区展示(不带测点)
     * @param
     * @return
     */
    @RequestMapping(value = "/readRoleOrgDmaList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询用户的所有 分区")
    public List<OrgBean> readRoleOrgDmaList(HttpServletRequest request){
        String type = request.getHeader("X-groupType");//type:1.系统默认 2.自定义
        Assert.isBlank(type,"用户类型不能为空");
        String companyCode = request.getHeader("X-Code");
        Assert.isBlank(companyCode,"系统编码不能为空");
        String roleId = request.getHeader("X-groupId");
        Assert.isBlank(roleId,"角色id不能为空");
        Long groupId = Long.valueOf(roleId);
        if(type.equals(1)){
            groupId = null;
        }
        //角色所有的分区
        List<OrgBean> objList = kyOrganizationService.selectByGroupIdAndCode(groupId,companyCode);
        return objList;
    }

    /**
     *根据顶级分区分区查询测点
     * @param
     * @return
     */
    @RequestMapping(value = "/getLongitudeAndLatitudeByOrgMaxId",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据顶级分区分区查询测点")
    public R getLongitudeAndLatitudeByOrgMaxId(int orgMaxId){
        Assert.isNull(orgMaxId,"系统分区id不能为空");
        List<Map<String,Object>> list = kyOrganizationEquipmentService.getEquipmentByOrgMaxId(orgMaxId);
        return R.ok().put("data",list);
    }
}